(function(root, factory){
  if( !root.FormDataUtils ){
    root.FormDataUtils = factory();
  }
})(this,function(){

  var FormDataUtils = function(json){
    this.jsonData = json || {};
    this.form = new FormData();
    this.getParam = '';
    this.init();    
  }

  FormDataUtils.prototype = {
    init: function () {
      for (const key in this.jsonData) {
        if (this.jsonData.hasOwnProperty(key)) {
          const element = this.jsonData[key];
          if( element ){
            this.getParam += ((/\?/).test(this.getParam) ? "&" : "?") + key + '=' + element;
          }
         
          if( this.jsonData.hasOwnProperty(key + 'Filename')){
            const name = this.jsonData[key + 'Filename'];
            this.form.append(key, element, name);
          }else{
            this.form.append(key, element);
          }
        }
      }
    },
    append: function( key, value, name){
      if ( name ) {
        this.form.append(key, value, name);
      }else{
        this.form.append(key, value);
      }
    },
    getForm: function(){
      return this.form;
    },
    send: function(url, success, error){
      var xhr = this.getHttpRequest();
      xhr.open('POST', url, true);
      xhr.onload = function(oEvent) {
        var data = xhr.responseText;
        if(data && typeof data === 'string'){
          try{data = eval(data);}catch(e){}	    			
        }
        if (xhr.status == 200) {
          if ( typeof success === 'function'){
            success(data);	    		
          }	      
        } else {
          if ( typeof error === 'function'){
            error(data);
          }
        }
      };
      xhr.send(this.form);
    },
    get: function(url, success, error){
      var xhr = this.getHttpRequest();
      url = url + this.getParam;
      xhr.open('GET', url);
      xhr.onload = function(oEvent) {
        var data = xhr.responseText;
        if(data && typeof data === 'string'){
          try{data = eval(data);}catch(e){}	    			
        }
        if (xhr.status == 200) {
          if ( typeof success === 'function'){
            success(data);	    		
          }	      
        } else {
          if ( typeof error === 'function'){
            error(data);
          }
        }
      };
      xhr.send(null);
    },
    getHttpRequest: function(){
      var xhr = null;
      if ( XMLHttpRequest ) {
        xhr = new XMLHttpRequest();
      }else if( ActiveXObject ){
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      }
      return xhr;
    }
  };
  return FormDataUtils;
});